package org.bbl.utils;

import com.google.inject.Binder;
import com.google.inject.name.Names;
import org.apache.log4j.Logger;
import org.bbl.common.Consumer;

import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class IoUtils {

    private static final Logger logger = Logger.getLogger(IoUtils.class.getName());


    public static void bindProperties(Binder binder, File file, File override) {
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(file));
            if (override.exists()) {
                Properties overRideProperties = new Properties();
                overRideProperties.load(new FileReader(override));
                for (Map.Entry<Object, Object> op : overRideProperties.entrySet()) {
                    properties.setProperty(op.getKey().toString(), op.getValue().toString());
                }
            }

            Names.bindProperties(binder, properties);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }

    public static String match(String regex, String candidate, Integer position) {
        Matcher matcher = Pattern.compile(regex).matcher(candidate);
        return matcher.find() ? matcher.group(position == null ? matcher.groupCount() : position) : null;
    }

    public static int processFile(File file, Consumer<String> consumer) {
        BufferedReader br = null;
        int lineCounter = 1;
        try {
            br = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), "UTF-8"));

            String line = br.readLine();
            while (line != null) {
                if (line.trim().length() != 0) {
                    consumer.consume(line, lineCounter);
                    lineCounter++;
                }

                line = br.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return lineCounter;
    }

    public static List<String> readFileToListOfLines(File file) {
        final List<String> result = new ArrayList<String>();
        try {
            processFile(file, new Consumer<String>() {
                @Override
                public void consume(String s, long lineNumber) {
                    result.add(s.trim());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getFileContent(File file) {
        return getFileContent(file,true);
    }

    public static String getFileContent(File file, final boolean addNewLine) {
        // final AtomicBoolean chapStarted = new AtomicBoolean(false);
        final StringBuilder builder = new StringBuilder();
        processFile(file, new Consumer<String>() {
            @Override
            public void consume(String message, long lineNumber) {
                //     if (chapStarted.get()) {
                builder.append(message) ;
                if(addNewLine){
                    builder.append("\n");
                }
            }
        });
        return builder.toString();

    }


    public static Map<String, String> processCSV(File file) {
        final Map<String, String> csv = new HashMap<String, String>();
        processFile(file, new Consumer<String>() {
            @Override
            public void consume(String message, long lineNumber) {
                String[] a = message.split(",",2);
                if(a.length==2){
                    csv.put(a[0], a[1]);
                }else{
                    System.out.println("short cvs line = " + message);
                }
            }
        });
        return csv;

    }

    public static void save(File fileName, String xml) {
        try {
            Writer writer = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(fileName), "UTF-8"));
            writer.append(xml);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
